package com.example.demo.Controller;


import com.example.demo.core.JsonUtil;
import com.example.demo.core.MD5Util;
import com.example.demo.core.NotFoundException;
import com.example.demo.core.Response;
import com.example.demo.core.security.JWTUtil;
import com.example.demo.model.Admin;
import com.example.demo.model.RolePermission;
import com.example.demo.model.User;
import com.example.demo.service.AdminService;
import com.example.demo.service.RolePermissionService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 管理员登入
     */
    @PostMapping("/login")
    public Object adminLogin(@RequestBody String body, HttpServletRequest request)
    {
        String name = JsonUtil.parseString(body, "name");
        String password = MD5Util.md5(JsonUtil.parseString(body, "password"));
        Admin admin=adminService.adminLogin(name, password);
        if(admin==null)
        {
            return Response.fail(508,"登录失败，用户名或密码错误");
        }
        rolePermissionService.selectByCondition(admin.getRole(),null);

        Map<String,String> map=new HashMap<String,String>();
        map.put("token",JWTUtil.getToken(String.valueOf(admin.getAdminId()),name,admin.getRole(),"admin",password));

        return Response.ok(map);
    }

    /**
     * 按照条件显示超级用户,条件全null显示所有超级用户
     * @param id
     * @param name
     * @param phone
     * @param email
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/info/select/all")
    @RequiresPermissions(logical = Logical.AND, value = {"admin:info:select:all"})
    public Object adminSelectByCondition(String id, String name, String phone,String email,
                                         @RequestParam(defaultValue = "1") Integer page,
                                         @RequestParam(defaultValue = "10") Integer limit) throws NotFoundException {
        if ("".equals(id))
            id=null;
        if ("".equals(name))
            name=null;
        if ("".equals(phone))
            phone=null;
        if ("".equals(email))
            email=null;

        List<Admin> admins=adminService.selectByCondition(id,name,phone,email,null);
        if (admins.size()==0)
            throw new NotFoundException("查询的超级用户为空");

        return Response.okList(admins,page,limit);//发list就行
    }


    /**
     * 查询自己的账号信息
     */
    @GetMapping(value = "/info/select/self")
    @RequiresAuthentication
    public Object selectSelfInfo(HttpServletRequest request)
    {
        String token=request.getHeader("Authorization");
        String id=JWTUtil.getId(token);
        List<Admin> admins=adminService.selectByCondition(id,null,null,null);
        if(admins.size()==0)
        {
            return Response.ok("Admin Not Found");
        }
        return Response.ok(admins.get(0));
    }

    /**
     * 修改自己的账号信息
     */
    @PostMapping("/info/update/self")
    @RequiresAuthentication
    public Object updateSelfInfo(@RequestBody String body, HttpServletRequest request)
    {
        String name = JsonUtil.parseString(body, "name");
        String phone = JsonUtil.parseString(body, "phone");
        String email = JsonUtil.parseString(body, "email");

        String token=request.getHeader("Authorization");
        String currentName=JWTUtil.getName(token);
        String id=JWTUtil.getId(token);
        if(!currentName.equals(name)&&adminService.selectByCondition(null,name,null,null).size()!=0)//说明重名
        {
            return Response.badArgumentValue();
        }
        return Response.ok(adminService.adminUpdate(new Admin(Integer.parseInt(id),name,null,phone,email,null,null)));
    }

    /**
     * 修改自己的密码
     */
    @PostMapping("/info/update/selfpassword")
    @RequiresAuthentication
    public Object updateSelfPassword(@RequestBody String body, HttpServletRequest request)
    {
        String oldPassword = MD5Util.md5(JsonUtil.parseString(body, "oldPassword"));
        String newPassword = MD5Util.md5(JsonUtil.parseString(body, "newPassword"));
        String token=request.getHeader("Authorization");
        String name=JWTUtil.getName(token);
        if(adminService.adminLogin(name, oldPassword)==null)
        {
            return Response.fail(401,"旧密码错误");
        }
        return Response.ok(adminService.adminUpdate(new Admin(Integer.parseInt(JWTUtil.getId(token)),null,newPassword,null,null,null,null)));
    }

    /**
     * 修改所有超级用户信息
     * @param body
     * @param request
     * @return
     */
    @PostMapping("/info/update/all")
    @RequiresPermissions(logical = Logical.AND, value = {"admin:info:update:all"})
    public Object adminUpdate(@RequestBody String body, HttpServletRequest request)
    {
        String id = JsonUtil.parseString(body, "id");
        String name = JsonUtil.parseString(body, "name");
        String password = MD5Util.md5(JsonUtil.parseString(body, "password"));
        String phone = JsonUtil.parseString(body, "phone");
        String email = JsonUtil.parseString(body, "email");
        String role = JsonUtil.parseString(body, "role");


        Admin admin=adminService.selectByCondition(id,null,null,null).get(0);
        if (!admin.getAdminName().equals(name)&&adminService.selectByCondition(null,name,null,null).size()>=1)
        {
            return Response.badArgumentValue("name");
        }
        return Response.ok(adminService.adminUpdate(new Admin(Integer.parseInt(id),name,password,phone,email,null,role)));
    }

    @PostMapping("/add")
    public Object addAdmin(@RequestBody String body, HttpServletRequest request)
    {
        String name = JsonUtil.parseString(body, "name");
        String password = MD5Util.md5(JsonUtil.parseString(body, "password"));
        String phone = JsonUtil.parseString(body, "phone");
        String email = JsonUtil.parseString(body, "email");
        //是否用户名重复
        if(adminService.selectByCondition(null,name,null,null).size()>=1)
        {
            return Response.fail(401,"该用户名已经存在");
        }
        return Response.ok(adminService.adminInsert(new Admin(null,name,password,phone,email,null,null)));
    }

    @PostMapping("/info/delete/all")
    @RequiresPermissions("admin:info:delete:all")
    public Object deleteAdmin(@RequestBody String body, HttpServletRequest request)
    {
        String id = JsonUtil.parseString(body, "id");
        List<Admin> admins=adminService.selectByCondition(id,null,null,null);
        if(admins.size()==0)
        {
            return Response.badArgumentValue();
        }
        return Response.ok(adminService.adminDelete(new Admin(Integer.parseInt(id),null,null,null,null,null,null)));
    }

    @GetMapping("/role/select")
    @RequiresAuthentication
    public Object selectRole(@RequestParam(defaultValue = "null") String role)
    {
        return Response
                .ok(rolePermissionService
                .selectByCondition(role, null)
                .stream()
                .map(RolePermission::getThePermission)
                .collect(Collectors
                        .toList()));
    }
}
